package com.cleaner.base.fragments

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import androidx.fragment.app.Fragment
import com.cleaner.base.utils.StatusBarUtils

abstract class BaseFragment : Fragment() {

    abstract fun getLayoutResId(): Int
    abstract fun onInitView(savedInstanceState: Bundle?)

    private val windowFocusChangeListener = ViewTreeObserver.OnWindowFocusChangeListener {
        onWindowFocusChange(it)
    }

    /**
     * 状态栏字体颜色是否是深色
     */
    protected open val isDark = true

    protected open fun onWindowFocusChange(hasFocus: Boolean) {
        // fragment不可见时不执行
        if (!hasFocus || isHidden) return
        StatusBarUtils.setTransparent(context)
        StatusBarUtils.setTextDark(context, isDark)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? = inflater.inflate(getLayoutResId(), container, false)

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        view.viewTreeObserver?.addOnWindowFocusChangeListener(windowFocusChangeListener)
        onInitView(savedInstanceState)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        view?.viewTreeObserver?.removeOnWindowFocusChangeListener(windowFocusChangeListener)
    }
}